package com.example.demo2.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo2.common.Result;
import com.example.demo2.entity.Customer;
import com.example.demo2.entity.DTO.OrderDTO;
import com.example.demo2.entity.Order;
import com.example.demo2.entity.ShopPlace;
import com.example.demo2.service.CustomerService;
import com.example.demo2.service.OrderService;
import com.example.demo2.service.ShopPlaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopPlaceService shopPlaceService;
    @Autowired
    private CustomerService customerService;

    @PostMapping("/add")
    public Result save(@RequestBody Order order) {
        order.setCreateTime(DateUtil.toLocalDateTime(new Date()));
        order.setState("审核中");
        boolean save = orderService.save(order);
        if (save) {
            return Result.success("200", "订单添加成功", save);
        } else {
            return Result.error("订单添加失败", "-1");
        }
    }

    @PostMapping("/cancel")
    public Result cancel(@RequestParam Integer id) {
        boolean save = orderService.removeById(id);
        if (save) {
            return Result.success("200", "订单取消成功", save);
        } else {
            return Result.error("订单取消失败", "-1");
        }
    }

    @PostMapping("/getOrderByPage")
    public Result getOrderByPage(@RequestBody OrderDTO orderDTO) {
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        if(orderDTO.getStartTime() != null && orderDTO.getEndTime() != null ){
            lqw.between(Order::getCreateTime,orderDTO.getStartTime(),orderDTO.getEndTime());
        }
        lqw.orderByDesc(Order::getCreateTime);
        lqw.eq(orderDTO.getState() !="",Order::getState,orderDTO.getState());
        Page<Order> ipage = new Page<>(orderDTO.getPage(), orderDTO.getLimit());
        Page<Order> page = orderService.page(ipage, lqw);
        page.getRecords().forEach(item -> {
            LambdaQueryWrapper<ShopPlace> shoplqw = new LambdaQueryWrapper<>();
            shoplqw.eq(ShopPlace::getId, item.getShopId());
            ShopPlace shop = shopPlaceService.getOne(shoplqw);
            item.setShopPlace(shop);
            LambdaQueryWrapper<Customer> customerlqw = new LambdaQueryWrapper<>();
            customerlqw.eq(Customer::getId, item.getUserId());
            Customer customer = customerService.getOne(customerlqw);
            item.setCustomer(customer);
        });
        return Result.success(page);
    }

    @GetMapping("/getOrderDetail")
    public Result getOrderByPage(@RequestParam Integer id) {
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getId, id);
        Order order = orderService.getOne(lqw);
        LambdaQueryWrapper<ShopPlace> shoplqw = new LambdaQueryWrapper<>();
        shoplqw.eq(ShopPlace::getId, order.getShopId());
        ShopPlace shop = shopPlaceService.getOne(shoplqw);
        order.setShopPlace(shop);
        LambdaQueryWrapper<Customer> customerlqw = new LambdaQueryWrapper<>();
        customerlqw.eq(Customer::getId, order.getUserId());
        Customer customer = customerService.getOne(customerlqw);
        order.setCustomer(customer);
        return Result.success(order);
    }

    @PostMapping("/examineOrderExamining")
    public Result examineOrderExamining(@RequestBody Integer id) {
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getId, id);
        Order order = orderService.getOne(lqw);
        if (order == null) {
            return Result.error("订单不存在", "-1");
        }
        order.setState("审核中");
        orderService.updateById(order);
        return Result.success(order);
    }
    @PostMapping("/examineOrderRight")
    public Result examineOrder(@RequestBody Integer id) {
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getId, id);
        Order order = orderService.getOne(lqw);
        if (order == null) {
            return Result.error("订单不存在", "-1");
        }
        order.setState("审核通过");
        orderService.updateById(order);
        return Result.success();
    }

    @PostMapping("/examineOrderError")
    public Result examineOrderError(@RequestBody Order order) {
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getId, order.getId());
        Order one = orderService.getOne(lqw);
        if (one == null) {
            return Result.error("订单不存在", "-1");
        }
        one.setState("审核不通过");
        one.setErrReason(order.getErrReason());
        orderService.updateById(one);
        return Result.success();
    }

    @PostMapping("/examineOrderFinish")
    public Result examineOrderFinish(@RequestBody Integer id) {
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getId, id);
        Order order = orderService.getOne(lqw);
        if (order == null) {
            return Result.error("订单不存在", "-1");
        }
        order.setState("订单已完成");
        orderService.updateById(order);
        return Result.success();
    }
    //批量删除
    @PostMapping("/batch/deleteOrder")
    public Result batchDeleteCity(@RequestBody List<Integer> ids) {
        return Result.success(orderService.removeBatchByIds(ids));
    }
    //批量审核
    @PostMapping("/batch/examineOrder")
    public Result batchexamineOrder(@RequestBody Order order) {
        List<Integer> ids = order.getIds();
        String state = order.getState();
        String errReason = "";
        if(order.getErrReason() != ""){
            errReason = order.getErrReason();
        }
        String finalErrReason = errReason;
        ids.forEach(item->{
            LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Order::getId,item);
            Order one = orderService.getOne(lqw);
            one.setState(state);
            one.setErrReason(finalErrReason);
            orderService.updateById(one);
        });
        return Result.success();
    }
    //批量导出v2.0 采用easyexcel方法
//        @ExcelProperty(value = "寄放点名称")
//    private String shopName;
//    @TableField(exist = false)
//    @ExcelProperty(value = "寄放城市")
//    private String shopCity;
//    @TableField(exist = false)
//    @ExcelProperty(value = "顾客昵称")
//    private String customerName;
//    @TableField(exist = false)
//    @ExcelProperty(value = "顾客手机号")
//    private String customerPhone;
    @GetMapping("/batch/newExportAllInfo")
    public void newBatchExportAllInfo(HttpServletResponse response, @RequestParam String ids) throws Exception {
        String[] split = ids.split(",");
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (String each : split) {
            arrayList.add(Integer.parseInt(each));
        }
        List<Order> idslist = orderService.listByIds(arrayList);
        idslist.forEach(item->{
            LambdaQueryWrapper<ShopPlace> shoplqw = new LambdaQueryWrapper<>();
            shoplqw.eq(ShopPlace::getId,item.getShopId());
            ShopPlace shop = shopPlaceService.getOne(shoplqw);
            item.setShopName(shop.getName());
            item.setShopCity(shop.getCompleteCity());
            LambdaQueryWrapper<Customer> customerlqw = new LambdaQueryWrapper<>();
            customerlqw.eq(Customer::getId,item.getUserId());
            Customer customer = customerService.getOne(customerlqw);
            item.setCustomerName(customer.getNickname());
            item.setCustomerPhone(customer.getPhone());
        });
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        EasyExcel.write(response.getOutputStream(), Order.class).autoCloseStream(Boolean.FALSE).sheet("表1").doWrite(idslist);
    }

}
